package com.it.xuehang.service.impl;

import com.it.xuehang.entity.ResourceCategory;
import com.it.xuehang.mapper.ResourceCategoryMapper;
import com.it.xuehang.service.ResourceCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资源类别。物资，装备，队伍，避难场所，防护目标等 服务实现类
 * </p>
 *
 * @author xuehang
 * @since 2024-12-10
 */
@Service
public class ResourceCategoryServiceImpl extends ServiceImpl<ResourceCategoryMapper, ResourceCategory> implements ResourceCategoryService {

    @Autowired
    private ResourceCategoryMapper resourceCategoryMapper;


    /**
     * 根据资源类别编码查询父级及其所有递归的下级类别数据。
     *
     * @param rescateId 资源类别编码
     * @return 包含父级和所有子类别的列表
     */
    public List<ResourceCategory> getCategoriesAndSubcategories(String rescateId) {
        List<ResourceCategory> result = new ArrayList<>();
        // 添加当前类别到结果列表中
        ResourceCategory currentCategory = resourceCategoryMapper.findById(rescateId).orElse(null);
        if (currentCategory != null) {
            result.add(currentCategory);
            // 递归添加所有子类别
            addSubcategories(result,currentCategory.getRescatecode());
        }
        return result;
    }

    /**
     * 递归添加所有子类别到结果列表中。
     *
     * @param result 结果列表
     * @param parentId 当前父类别ID
     */
    private void addSubcategories(List<ResourceCategory> result, String parentId) {
        List<ResourceCategory> subCategories = resourceCategoryMapper.findByRescateParentId(parentId);
        if (subCategories != null && !subCategories.isEmpty()) {
            for (ResourceCategory subCategory : subCategories) {
                result.add(subCategory);
                // 递归调用以添加子类别的子类别
                addSubcategories(result, subCategory.getRescatecode());
            }
        }
    }

}
